const express = require('express')
const cors = require('cors')
const mysql = require('mysql2')
const crypto = require('crypto')
const cheerio = require('cheerio')
const multer = require('multer');
const formidable = require('formidable')
const path = require('path')
const fs = require('fs')
const tool = require('./tool')
const xlsx = require('xlsx')
const http = require('http')
const axios = require('axios')

const connectionConfig = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'szt',
    port: 3306
}

const config = {
    port: 3000,
    prefix: '/api'
}

const connection = mysql.createConnection(connectionConfig);

console.clear()

function connectDatabase() {
    return new Promise((resolve, reject) => {
        connection.connect(err => {
            return resolve(err == null ? 'OK' : err.toString())
        })
    })
}

function execSQL(SQL) {
    return new Promise((resolve, reject) => {
        connection.query(SQL, (error, results, fields) => {
            if (error) {
                console.log(error)
                return reject()
            }
            return resolve(results)
        })
    })
}

function axiosGetWebSite(url){
    return new Promise((resolve, reject) => {
        axios.get(url)
        .then(response => {
            resolve(response.data)
        }).catch(err=>{
            resolve('')
        })
    })
}

async function main() {

    try {

        console.clear()

        let re = await connectDatabase()

        if (re != 'OK') {
            console.log('szt server 未能正常启动，原因：' + re)
            process.exit(0)
        }

        const app = express();
        app.use(express.json())
        app.use(cors())

        const storage = multer.diskStorage({
            destination: 'files/',
            filename: function (req, file, cb) {
                const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
                const fileExtension = path.extname(file.originalname);
                cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
            }
        })

        const upload = multer({ storage: storage })

        app.post(config.prefix + '/news/preview', async (req, res) => {
            try {
                data = req.body
                if (data == null) {
                    res.send('非法请求')
                    return
                }
                //
                let re = {
                    searchBox:[]
                }
                for(let i=0;i<Object.keys(tempData.news).length;i++){
                    if(tempData.news[Object.keys(tempData.news)[i]].length){
                        re.searchBox.push(tempData.news[Object.keys(tempData.news)[i]][0])
                    }
                }
                tool.resSend(res, 1, '成功', re)
            } catch (error) {
                console.log(error)
                tool.resSend(res, -2, '系统内部错误', undefined)
            }
        })

        app.post(config.prefix + '/file/upload', upload.single('file'), async (req, res) => {
            if (!req.file) {
                res.status(400).json({ error: '上传失败' });
            } else {
                res.json({
                    status: 1,
                    content: '上传成功',
                    results: req.file.filename
                })
            }
        })

        app.get(config.prefix + '/file/download/:filename', async (req, res) => {
            const filename = req.params.filename;
            const filePath = path.join('files', filename);
            if (!fs.existsSync(filePath)) {
                return res.status(404).json({
                    status: 0,
                    content: '无此文件'
                });
            }
            res.setHeader('Content-Disposition', `filename=${filename}`);
            const fileStream = fs.createReadStream(filePath);
            fileStream.pipe(res);
        })

        app.get('', (req, res) => {
            res.send('普语精进后端已启动')
        })

        app.use(express.json({ limit: '50mb' }))
        app.use(express.urlencoded({ extended: true, limit: '50mb' }))

        app.listen(config.port, async () => {
            console.log('\x1b[32mpyjj server 已启动.\x1b[37m')
            console.log('port:' + config.port.toString())
        })

    } catch (error) {
        console.log(error)
    }

}

main()